<?php

namespace haibao\erp\data\usergroup;


class UserGroup extends \haibao\erp\data\BaseMysql{
    
	public function __construct(){
		parent::__construct('\haibao\erp\model\data\usergroup\UserGroupDefine');
	}
	
	public function saveGroup($groupId,$arrSet){
		$this->beginTranscation();
		try{
			parent::updateById($groupId, $arrSet);
			$sql ="delete from UserGroupPermission where GroupId=%s";
			$this->query($sql,array($groupId));
				
			$arrSql = array();
			$arrValues = array();
			$insert_sql = "insert into UserGroupPermission(GroupId,FunctionCode) values";
			foreach($arrSet[\haibao\erp\model\filter\usergroup\UserGroupDefine::CONDITION_FIELD_FUNCODES] as $funcCode){
				array_push($arrSql,'(%s,%s)');
				array_push($arrValues,$groupId);
				array_push($arrValues,$funcCode);
			}
			$insert_sql .= implode(',', $arrSql);
			$this->query($insert_sql,$arrValues);
				
			$cache = new \haibao\erp\cache\UserGroup();
			$cache->removeFuncCodesByGroupId($groupId);
		}
		catch(\Exception $e){
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	public function getFuncCodesByGroupIds($groupIds){
		$data = array();
		$cache = new \haibao\erp\cache\UserGroup();
		$ids = array();
		foreach ($groupIds as $groupId){
			$codes = $cache->getFuncCodesByGroupId($groupId);
			if ($codes){
				$data[$groupId] = $codes;
			}
			else{
				array_push($ids,$groupId);
			}
		}
	
		if ($ids){
			$sql = 'select GroupId,FunctionCode from UserGroupPermission where GroupId in ('.implode(',',$ids).')';
			$result = $this->query($sql);
			$codes = array();
			while ($result->fetch_assoc()){
				$groupId = $result->getData('GroupId');
				$functionCode = $result->getData('FunctionCode');
				if (!isset($codes[$groupId])){
					$codes[$groupId] = array();
				}
	
				array_push($codes[$groupId],$functionCode);
			}
				
			if ($codes){
				foreach ($codes as $groupId=>$value){
					$cache->setFuncCodesByGroupId($groupId,$value);
					$data[$groupId] = $value;
				}
			}
		}
	
		return $data;
	}
	
	/**
	 * 添加用户组
	 */
	public function add($model){
		$this->beginTranscation();
		try{
			$model->OrderSort = 0;
			parent::add($model);
			if($model->FuncCodes){
				$sql = 'insert into UserGroupPermission(GroupId,FunctionCode) values';
				$arrSql = array();
				$arrValues = array();
				foreach($model->FuncCodes as $funcCode){
					array_push($arrSql,'(%s,%s)');
					array_push($arrValues,$model->Id);
					array_push($arrValues,$funcCode);
				}
				$sql .= implode(',',$arrSql);
				$this->query($sql,$arrValues);
			}
		}
		catch(\Exception $e){
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
	}
	
	
}
